package com.hh.game.service.gateway.manager.service.config;

import cn.hutool.core.io.file.FileNameUtil;
import org.springframework.core.io.Resource;

import java.io.File;
import java.io.IOException;

public class DefaultConfigResource implements ConfigResource {
    private String dataId;
    private Object data;
    private ConfigType type;
    private Resource resource;

    public DefaultConfigResource(String dataId ,Object data) {
        this.data = data;
        this.type = ConfigType.JSON;
        this.dataId = dataId;
    }
    public DefaultConfigResource(String dataId ,Object data ,ConfigType type) {
        this.data = data;
        this.type = type;
        this.dataId = dataId;
    }

    public DefaultConfigResource(Resource resource ,ConfigResourceReader resourceReader) {
        try {
            this.dataId = resource.getURI().toString();
        }catch (Exception e){
        }
        this.resource = resource;
        this.data = resourceReader.read(this);
        if(resource.isFile()){
            try {
                File file = resource.getFile();
                String ext = FileNameUtil.extName(file);
                this.type = ConfigType.parseConfigType(ext);
            }catch (Exception e){
            }
        }
    }

    @Override
    public boolean isFile() {
        return resource != null && resource.isFile();
    }

    @Override
    public Object getData() {
        return data;
    }

    @Override
    public File getFile() throws IOException {
        return resource == null ? null : resource.getFile();
    }

    @Override
    public ConfigType getType() {
        return type;
    }

    @Override
    public String getDataId() {
        return dataId;
    }

    @Override
    public boolean isEmpty() {
        return getData() == null;
    }
}
